package com.tcr.core;

import org.apache.log4j.Logger;

import com.tcr.common.ZipTask;
import com.tcr.dao.CoverageDao;
import com.tcr.util.FileUtil;

public class UnzipCron extends Thread {

	private final static int CRONTIME = 30 * 1000;

	public UnzipCron() {
		queue = ZipQueue.getInstance();
	}

	public void run() {
		while (true) {
			try {
				ZipTask task = queue.getTask();
				if (task == null) {
					logger.info("The queue is empty");
					try {
						Thread.sleep(CRONTIME);
						continue;
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						logger.error(e);
					}
				}

				boolean b = false;

				b = UnZipHandler.unzip(task.file_path, task.output);

				if (b) {
					logger.info("Unzip the file success , src_path ="
							+ task.file_path + "%%output=" + task.output);

					FileUtil.deleteFile(task.file_path);
					logger.info("delete the zip_file = " + task.file_path);

					String c_dir = "/tcr/upload/" + task.fname
							+ System.getProperty("file.separator") + task.index;
					String c_version = task.version;
					int pid = task.pid;
					int uid = task.uid;

					logger.info(String.format(
							"c_dir=%s,c_version=%s,pid=%d,uid=%d", c_dir,
							c_version, pid, uid));

					CoverageDao.add_cov(pid, c_dir, c_version, uid);

					logger.info("Insert into tc_cov");
				} else {
					logger.info("The file unzip error " + task.file_path);
				}

				try {
					Thread.sleep(CRONTIME);
					continue;
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					logger.error(e);
				}
			} catch (Exception ex) {
				logger.error(ex);
			}
		}
	}

	public String cutZipExtension(String src) {
		int lasttag = src.lastIndexOf("/");
		int index = src.indexOf(".zip");
		return src.substring(lasttag, index);
	}

	private final static Logger logger = Logger.getLogger(UnzipCron.class);
	private ZipQueue queue;
}
